const {cloneDeep} = require('loadsh')
let print = null

// 遍历处理打印参数
function anasysArgument(data,originLog){
    print = originLog
    const dataArr =[]
    Object.keys(data).forEach(key=>{
        dataArr[key]=data[key]
    })
    return dataArr.map((param,index)=>{
        return makeParameter(param)
    })
}

/**
 * 递归填充数据信息
 */
function  makeParameter(param,level=0,key){
    const res = typeof param === 'function'? param:cloneDeep(param)
    if(res && res.type){
        return res
    }
    let type = ''
    let source = res
    // let origin = cloneDeep(res)
    let origin = handleOrigin(param)
    let funcName = ''
    if(typeof res ==='undefined'){
        type = 'Undefined'
        source='undefined'
        origin = 'undefined'
    }else if(!res && typeof res ==='object'){
        type = 'Null'
        source='null'
        origin = 'null'
    }else if(Array.isArray(res)){
        type='Array'
        
        source = res.map((item,index)=>makeParameter(item,level+1,index))
    }else if(typeof res ==='object'){
        type='Object'
        Object.keys(res).forEach(key=>{
            res[key]=makeParameter(res[key],level+1,key)
        })

    }else if(typeof res==='function'){
        type='Function'


        // 普通函数定义
        funcName = res.name || 'ANONYMOUS'
        if(res.toString().indexOf('function')>-1){

            
            source = res.toString()
            // function funName 的定义
            if(source.split('(')[0].indexOf(funcName)>-1){

                source =source.replace(` ${funcName}`,'')
            
            }
            source = source.replace('function',`function ${funcName}`)

        }
        else{
            source = res.toString()
        }
        
        
        origin = source
        source = ` functionSpace.${funcName} = ${source}` 
    }else if (typeof res === 'string'){
        type = 'String'
    }else if (typeof res === 'number'){
        type = 'Number'
    }else if (typeof res === 'boolean'){
        type = 'Boolean'
    }

    return {
        type,
        source,
        origin,
        level,
        ...((res && (typeof res === 'object'||typeof res === 'function'))&&{flod:true}),
        ...(funcName && {funcName}),
        ...(key&&{keyName:key})
    }
}

// 递归处理层级中的函数,将函数的值改为'ƒ'字符串
const handleOrigin =(param)=>{
    let res = param
    if(res && typeof res == 'object'){
        Object.keys(res).forEach(key=>{
            res[key] = handleOrigin(res[key])
        })
    }else if(typeof res === 'function'){
        res = 'ƒ'
    }
    return res
}


module.exports = {anasysArgument}